<template>
  <div>
    <!--  面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!--      消息提示的文案-->
      <el-alert
        title="编辑商品信息" show-icon center :closable="false"
        type="info">
      </el-alert>
      <!--      步骤条-->
      <el-steps :space="200" :active="activeIndex" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsFormRef" label-width="100px">
        <!--      tabs标签页 before-leave切换标签之前的钩子  @tab-click="tabClick"-->
        <el-tabs :tab-position="'left'"  :before-leave="beforeLeave"  @tab-click="tabClick">
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price" >
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" >
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" >
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat" >
              <el-cascader
                v-model="selectCateKeys"
                :options="cateList"
                :props="props"
                @change="handleChange" clearable ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <!-- 渲染表单的Item项 -->
            <el-form-item v-for="(item1 ) in manyTableData" :key="item1.attr_id" :label="item1.attr_name">
              <!--            这里双向绑定了 v-model="item1.attr_vals"-->
              <el-checkbox-group  v-model="item1.attr_vals">
                <!--             label与数组中的元素值相对应，如果存在指定的值则为选中状态，否则为不选中。-->
                <el-checkbox border v-for="(item2 ,i) in item1.attr_vals" :key="i" :label="item2" style="margin: 15px"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" >
            <el-form-item :label="item.attr_name" v-for="item in this.onlyTableData" :key="item.attr_id" label-width="150px">
              <!--            这里双向绑定了 v-model="item.attr_vals"-->
              <el-input v-model="item.attr_value"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" >
            <!--  action 图片上传url          -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove" :on-success="uploadSuccess" :file-list="fileList"
              list-type="picture" :headers="headersObj">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" >
            <!--          富文本编辑器 导入依赖vue-quill-editor 然后导入main.js中全局使用-->
            <quill-editor v-model="addGoodsForm.goods_introduce">
            </quill-editor>
            <!--          商品添加按钮-->
            <el-button type="primary" @click="editGood" style="margin-top: 15px">修改商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!--      图片预览弹框-->
      <el-dialog
        title="图片预览"
        :visible.sync="prePictureVisible"
        width="50%">
        <img :src="prePicUrl" alt="" width="100%">
        <span slot="footer" class="dialog-footer">
  </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// import _ from 'lodash'
export default {
  data() {
    return {
      // 图片预览文件集合
      fileList: [],
      // 当前激活步骤条的index的下标值
      activeIndex: 0,
      // 商品表单
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 分类列表 字符串（selectCateKeys转换过来）
        goods_cat: [],
        // 上传的图片临时路径（对象）
        pics: [],
        // 商品介绍
        goods_introduce: '',
        // 商品动态参数或静态属性
        attrs: []
      },
      // 商品表单验证规则
      addGoodsFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品分类', trigger: 'blur' }]
      },
      // 所有分类列表
      cateList: [],
      //    prop配置选项 expandTrigger次级菜单的展开方式 value指定选项的值为选项对象的某个属性值
      // label指定选项标签为选项对象的某个属性值 children指定选项的子选项为选项对象的某个属性值
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 父级id列表
      selectCateKeys: [],
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      // 图片上传url
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传设置上传的请求头部
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览开关
      prePictureVisible: false,
      // 图片预览url
      prePicUrl: '',
      // 商品的详细信息
      GoodsInfo: {}

    }
  },
  created () {
    this.getCateList()
    this.getGoodInfo()
  },
  methods: {
    // tab页签点击事件监听
    async tabClick (tab) {
      // console.log(tab.index === '1')
      if (tab.index === '1') {
        const manyAttrs = this.GoodsInfo.attrs.filter(item => item.attr_sel === 'many')
        this.manyTableData = manyAttrs
        console.log(this.manyTableData)
        // 将attr_vals字符串变为数组
        this.manyTableData.forEach(item => {
          // 这里判断是为了防止用户返回上一层级报错
          if (typeof (item.attr_vals) === 'string') {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          }
        })
      } else if (tab.index === '2') {
        const onlyAttrs = this.GoodsInfo.attrs.filter(item => item.attr_sel === 'only')
        console.log(onlyAttrs)
        this.onlyTableData = onlyAttrs
      }
    },
    // 获取所有的分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('获取商品分类列表失败！') }
      // this.$message.success('获取商品分类列表成功！')
      this.cateList = res.data
    },
    // 获取商品详细信息
    async getGoodInfo () {
      // 根据 ID 查询商品
      const goodId = this.$route.params.goodId
      // alert(goodId)
      const { data: goodRes } = await this.$http.get('goods/' + goodId)
      console.log(goodRes)
      if (goodRes.meta.status !== 200) {
        return this.$message.error('获取商品详细信息失败！')
      }
      this.GoodsInfo = goodRes.data
      // 初始化商品的基本信息
      this.addGoodsForm.goods_name = goodRes.data.goods_name
      this.addGoodsForm.goods_price = goodRes.data.goods_price
      this.addGoodsForm.goods_number = goodRes.data.goods_number
      this.addGoodsForm.goods_weight = goodRes.data.goods_weight
      this.addGoodsForm.goods_cat = [goodRes.data.cat_one_id, goodRes.data.cat_two_id, goodRes.data.cat_three_id]
      this.addGoodsForm.goods_introduce = goodRes.data.goods_introduce
      this.selectCateKeys = [goodRes.data.cat_one_id, goodRes.data.cat_two_id, goodRes.data.cat_three_id]
      if (goodRes.data.pics) {
        goodRes.data.pics.forEach(item => {
          this.fileList.push({ url: item.pics_big_url })
          // const url = 'tmp_uploads\\' + item.pics_big_url.substring(item.pics_big_url.lastIndexOf('/') + 1)
          // this.addGoodsForm.pics.push({ pic: url })
        })
      }
    },
    // 监听级联选择框发生变化
    handleChange() {
      // 不能选择非三级的其他节点
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
      }
      this.addGoodsForm.goods_cat = this.selectCateKeys
    },
    // 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。
    beforeLeave(activeName, oldName) {
      if (activeName === '0') {
        return true
      }
      // console.log(activeName + '  ' + oldName)
      if (this.selectCateKeys.length !== 3) {
        this.$message.error('请填写商品分类')
        this.activeIndex = parseInt(oldName)
        return false
      }
      this.activeIndex = parseInt(activeName)
    },
    // 移除图片
    handleRemove(file) {
      // alert(1)
      // array.splice(start,delCount);//从start的位置开始向后删除delCount个元素
      // console.log(this.addGoodsForm.pics)
      // array.findIndex() 寻找下标方法
      const i = this.addGoodsForm.pics.findIndex(x => {
        const url = 'tmp_uploads\\' + file.url.substring(file.url.lastIndexOf('/' + 1))
        if (x.pic === url) { return x }
      }
      )
      this.addGoodsForm.pics.splice(i, 1)
      // console.log(this.addGoodsForm.pics)
    },
    // 图片上传预览
    handlePreview(file) {
      console.log(file)
      this.prePictureVisible = true
      this.prePicUrl = file.response.data.url
    },
    // 图片上传成功的勾子方法
    uploadSuccess(response) {
      console.log(response)
      const pictureInfo = { pic: response.data.tmp_path }
      this.addGoodsForm.pics.push(pictureInfo)
      // console.log(this.addGoodsForm)
      this.fileList.push({ url: response.data.url })
    },
    // 修改商品
    async editGood () {
      // console.log(this.addGoodsForm.goods_introduce)
      // 先进行预先验证
      this.$refs.addGoodsFormRef.validate(valid => {
        if (!valid) return this.$message.error('请填写表单的必要项')
      })
      // 提交表单
      if (typeof (this.addGoodsForm.goods_cat) !== 'string') {
        this.addGoodsForm.goods_cat = this.addGoodsForm.goods_cat.join(',')
        // console.log(this.addGoodsForm.goods_cat)
      }
      // 处理动态参数
      this.manyTableData.forEach(item => {
        const manyAttr = {
          attr_id: item.attr_id,
          // 数组转字符串
          attr_value: item.attr_vals.join(' ')
        }
        this.addGoodsForm.attrs.push(manyAttr)
      })
      // 处理静态属性
      this.onlyTableData.forEach(item => {
        const onlyAttr = {
          attr_id: item.attr_id,
          attr_value: item.attr_value
        }
        this.addGoodsForm.attrs.push(onlyAttr)
      })
      console.log(this.addGoodsForm)
      // 向后台发起修改商品请求
      const goodId = this.$route.params.goodId
      // alert(goodId)
      const { data: res } = await this.$http.put('goods/' + goodId, this.addGoodsForm)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('修改商品失败')
      }
      this.$message.success('修改商品成功！')
      this.$router.push('/goods')
    }
  }
}
</script>

<style scoped>

</style>
